package com.husd.framework.util;

import okhttp3.*;

import java.io.IOException;
import java.util.Map;

public class OkHttpUtil {

    private static final OkHttpClient client = new OkHttpClient();
    private static final MediaType MEDIA_TYPE_JSON = MediaType.get("application/json; charset=utf-8");

    public static String get(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    public static String post(String url, Map<String, String> headerMap,
                              Map<String, String> formMap) throws IOException {

        FormBody.Builder formBuilder = new FormBody.Builder();

        if (formMap != null && formMap.size() > 0) {
            for (Map.Entry<String, String> entry : formMap.entrySet()) {
                formBuilder.add(entry.getKey(), entry.getValue());
            }
        }

        FormBody formBody = formBuilder.build();

        Request.Builder builder = new Request.Builder().url(url);

        if (headerMap != null && headerMap.size() > 0) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                builder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        Request request = builder.post(formBody).build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    public static String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

}
